// web/src/app/learn/(dashboard)/(routes)/teacher/courses/[courseId]/chapters/[chapterId]/_components/chapter-access-form.tsx
'use client';
import React, {useState} from 'react';
import {Chapter} from "@prisma/client";
import * as z from "zod";
import {useRouter} from "next/navigation";
import {useForm} from "react-hook-form";
import {zodResolver} from "@hookform/resolvers/zod";
import toast from "react-hot-toast";
import {Button} from "@/components/ui/button";
import {Pencil} from "lucide-react";
import {cn} from "@/lib/utils";
import Preview from "@/components/learn/preview";
import {Form, FormControl, FormDescription, FormField, FormItem, FormMessage} from "@/components/ui/form";
import Editor from "@/components/learn/editor";
import {Checkbox} from "@/components/ui/checkbox";

interface Props {
    initialData: Chapter
    courseId: string
    chapterId: string
}

const formSchema = z.object({
    isFree: z.boolean().default(false)
})

const ChapterAccessForm = ({
                               initialData, courseId, chapterId,
                           }: Props) => {

    const router = useRouter()

    const [isEditing, setIsEditing] = useState(false)
    const toggleEdit = () => setIsEditing((current) => !current)

    const form = useForm<z.infer<typeof formSchema>>({
        resolver: zodResolver(formSchema),
        defaultValues: {
            isFree: !!initialData.isFree
        }
    })

    const {isSubmitting, isValid} = form.formState

    const onSubmit = async (values: z.infer<typeof formSchema>) => {
        try {
            const res = await fetch(`/api/course/${courseId}/chapters/${chapterId}`, {
                method: "PATCH",
                body: JSON.stringify(values),
                headers: {
                    "Content-Type": "application/json"
                }
            })
            if (!res.ok) throw new Error(`failed fetch`)
            toast.success(`更新成功`)
            toggleEdit()
            router.refresh()
        } catch (err) {
            toast.error(`Something went wrong`)
            console.error('Something went wrong', err);
        }
    }

    return (
        <div className={`mt-6 border bg-slate-100 rounded-md p-4`}>
            <div className={`font-medium flex items-center justify-between`}>
                Chapter access
                <Button variant={'ghost'}
                        onClick={toggleEdit}>
                    {isEditing ? (
                        <>Cancel</>
                    ) : (
                        <>
                            <Pencil className={`size-4 mr-2`}/>
                            Edit chapter access
                        </>
                    )}
                </Button>
            </div>
            {!isEditing && (
                <p className={cn(
                    `text-sm mt-2`,
                    !initialData.isFree && `text-slate-500 italic`
                )}>
                    {initialData.isFree ? (
                        <>This chapter is free for preview.</>
                    ) : (
                        <>This chapter is no free.</>
                    )}
                </p>
            )}
            {isEditing && (
                <Form {...form}>
                    <form
                        onSubmit={form.handleSubmit(onSubmit)}
                        className={`space-y-4 mt-4`}
                    >
                        <FormField
                            control={form.control}
                            name={'isFree'}
                            render={({field}) => (
                                <FormItem className={`flex flex-row items-start space-x-3 space-y-0 
                                rounded-md border p-4`}>
                                    <FormControl>
                                        <Checkbox
                                            checked={field.value}
                                            onCheckedChange={field.onChange}
                                        />
                                    </FormControl>
                                    <div className={`space-y-1 leading-none`}>
                                        <FormDescription>
                                            Check this box if you want to make this chapter free for preview
                                        </FormDescription>
                                    </div>
                                </FormItem>
                            )}
                        />
                        <div className={`flex items-center gap-x-2`}>
                            <Button
                                disabled={!isValid || isSubmitting}
                                type={'submit'}
                            >
                                Save
                            </Button>
                        </div>
                    </form>
                </Form>
            )}
        </div>
    );
};

export default ChapterAccessForm;